//
//  CZLayout.m
//  瀑布流
//
//  Created by apple on 15/12/31.
//  Copyright © 2015年 apple. All rights reserved.
//

#import "TZLayout.h"

#import "TZPBLModel.h"
@interface TZLayout ()


@property (strong,nonatomic)NSMutableArray *atts;

@end

@implementation TZLayout


- (NSMutableArray *)atts
{
    if (_atts == nil) {
        
        _atts = [NSMutableArray array];
    }

    return _atts;
}

//itemsize   滚动方向
- (void)prepareLayout
{
    [super prepareLayout];
    
    
    //往数组里面添加Attributes对象
    //多少个
    
    
    //宽度  由列数 和 间隙   内边距
    
    int colCount = 3;
    
    //用一个 C 语言的数组保存列高
    
    CGFloat colHeights[colCount];
    
    for (int i = 0; i <colCount; i ++) {
        
        colHeights[i] = self.sectionInset.top;
    }
    
    
    
    
    
//    CGFloat itemW = (总宽度 - (列数 - 1 ) *间隙 )  / 列数;
    
    CGFloat contentW = (self.collectionView.frame.size.width - (colCount - 1 ) *self.minimumInteritemSpacing);
     CGFloat itemW = contentW  / colCount;
    
   
    for (int i = 0; i < self.shops.count; i ++) {
        
        
        TZPBLModel *shop = self.shops[i];
        
        
        CGFloat itemH = shop.h / shop.w * itemW;
        
        //设置 x
        
        int col = i % colCount;
        
        
        CGFloat itemX = col * (itemW + self.minimumInteritemSpacing);
        
        //设置 Y
        //跟谁有关系
        //第几行
        
        //创建Attributes对象
        UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
        
        //设置 frame
        //设置相对应的位置
        att.frame = CGRectMake(itemX, colHeights[col] , itemW, itemH);
        
        colHeights[col] += itemH + self.minimumLineSpacing;
        
        [self.atts addObject:att];
    }

    //获取想要的滚动范围
    //是数组里面最大的一个值
    //遍历数组获取最大值
    
    CGFloat maxH = 0;
    
    for (int i = 0; i < colCount; i ++) {
        
        if (maxH < colHeights[i]) {
            
            maxH = colHeights[i];
        }
      
    }
    
//    CGFloat H = 滚动范围  / 行数
    
    
    //计算行数
    CGFloat row;
    
    if (self.shops.count % (int)colCount == 0 ) {
        
        row = self.shops.count / colCount;
    }else{
        row = self.shops.count / colCount + 1;
    
    }
    
    CGFloat H = maxH / row;
    
    //itemSize
    //滚动范围 和 itemSize 有关系  系统会根据itemSize自动决定滚动范围
    self.itemSize = CGSizeMake(itemW, H);
    
    

}


- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{

    NSArray *arr = [super layoutAttributesForElementsInRect:rect];
    

    
    return self.atts;

}

@end
